//
//  XBRefreshView.swift
//  sinaDemo
//
//  Created by mac on 15/12/22.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

import UIKit
import SnapKit

enum XBRefreshViewType: Int {
    // 默认状态
    case normal = 0
    // 用户正在下拉状态
    case pull = 1
    // 正在刷新状态
    case refresh = 2
}

class XBRefreshView: UIControl {
    
    // 高度
    let refreshViewH:CGFloat = 60
    
    // 定义状态记录上一次的状态
    var oldState: XBRefreshViewType = .normal
    
    // 定义状态属性,重写setter方法,给属性赋值
    var refreshState: XBRefreshViewType = .normal {
        didSet {
            switch refreshState {
            case .pull:
                tipLabel.text = "准备起飞"
                // 旋转箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .refresh:
                tipLabel.text = "正在起飞"
                // 显示菊花,并且开始动画,隐藏箭头
                arrowIcon.hidden = true
                indicater.startAnimating()
                // 向下偏移scrollview
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView?.contentInset
                    inset?.top += self.refreshViewH
                    self.scrollView?.contentInset = inset!
                })
                // 主动触发control事件
                sendActionsForControlEvents(.ValueChanged)
                
            case .normal:
                // 菊花停止动画,显示箭头
                tipLabel.text = "下拉起飞"
                arrowIcon.hidden = false
                indicater.stopAnimating()
                // 如果上次是刷新状态,那么把偏移变为原来的偏移
                if oldState == .refresh {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView?.contentInset
                        inset?.top -= self.refreshViewH
                        self.scrollView?.contentInset = inset!
                    })
                    // 重置箭头方向
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.arrowIcon.transform = CGAffineTransformIdentity
                    })
                }
            }
            
            oldState = refreshState
        }
    }
    
    // 结束刷新状态
    func endRefresh() {
        // 延迟的秒数
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(2) * Int64(NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) { () -> Void in
            self.refreshState = .normal
        }
    }
    
    override init(frame: CGRect) {
        let rect: CGRect = CGRectMake(0, -refreshViewH, screenBoundsWidth, refreshViewH)
        super.init(frame: rect)
        // 初始化子控件
        setUpUI()
        // 设置随机颜色
//        backgroundColor = UIColor.randomColor()
    }
    
    // 初始化子控件
    private func setUpUI() {
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicater)
        
        // 设置约束
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        // 箭头
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        // 菊花
        indicater.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self.snp_centerY)
            make.right.equalTo(tipLabel.snp_left)
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        // 记录父view
        if let myFather = newSuperview as? UIScrollView {
            scrollView = myFather
            // 设置KVO
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    // 移除观察者
    deinit {
        removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // KVO观察调用方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // tableview的上边距
        let top = scrollView?.contentInset.top ?? 0
        // 获取临界值,如果大于临界值需要改变状态
        let criticalValue = -(refreshViewH + top)
        // 获取偏移量
        let offsetY = scrollView?.contentOffset.y
        print(offsetY)
        // 判断是否正在拖拽
        if scrollView!.dragging { // 正在拖拽
            // 判断是否超过临界值
            if refreshState == .normal && offsetY < criticalValue { // 用户正在下拉
                // 把状态改为下拉状态
                refreshState = .pull
            }else if refreshState == .pull && offsetY > criticalValue { // 下拉超过临界值后,然后在会去的时候会走到这里
                // 把状态改为默认状态
                refreshState = .normal
            }
        }else { // 不再拖拽,松手的时候马上小于临界值的时候,进入刷新状态
            if refreshState == .pull {
                refreshState = .refresh
            }
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: 懒加载
    
    // 引用父view
    var scrollView: UIScrollView?
    
    // 提示label
    private var tipLabel: UILabel = UILabel(title: "下拉起飞", color: UIColor.lightGrayColor(), textFont: 14)
    
    // 箭头label
    private var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    // 菊花
    private var indicater: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)

}
